package com.shouyun.modules.security.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shouyun.common.constant.Constant;
import com.shouyun.common.utils.DataUtils;
import com.shouyun.common.utils.DateUtils;
import com.shouyun.common.utils.Result;
import com.shouyun.modules.security.oauth2.TokenGenerator;
import com.shouyun.modules.security.service.SysUserTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SysUserTokenServiceImpl implements SysUserTokenService {
    /**
     * 12小时后过期
     */
    private final static int EXPIRE = 3600 * 12;
    /**
     * 有效期-天
     */
    private final static int EXPIRE_DAY = 360;

    @Override
    public Result createToken(String token, JSONObject user) {
        //生成一个token
        if (StringUtils.isBlank(token)) {
            token = TokenGenerator.generateValue();
        }

        //当前时间
        Date now = new Date();
        //过期时间
//        Date expireDate = new Date(now.getTime() + EXPIRE * 1000);
        Date expireDate = DateUtils.addDateDays(now, EXPIRE_DAY);
        //保存token
        user.put("lastDate", expireDate);
        DataUtils.setData(DataUtils.TOKEN, token, user);
        //获取授权标识
        Map<String, Object> map = new HashMap<>(2);
        map.put(Constant.TOKEN_HEADER, token);
        map.put("expire", EXPIRE);
        map.put("userDetail", user);
        return new Result().ok(map);
    }

    @Override
    public void logout(String token) {
        //删除token
        DataUtils.removeData(DataUtils.TOKEN, token);
    }

    @Override
    public JSONObject getByToken(String token) {
        return DataUtils.getData(DataUtils.TOKEN, token);
    }
}